import 'dart:async';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chip/bean/User.dart';
import 'package:flutter_chip/config/Api.dart';
import 'package:flutter_chip/config/Http.dart';
import 'package:flutter_chip/utils/comm_utils.dart';
import 'package:flutter_chip/utils/toast_utils.dart';
import 'package:provide/provide.dart';

class EmailPage extends StatefulWidget {
  final String email;

  const EmailPage({Key key, this.email}) : super(key: key);

  @override
  _EmailPageState createState() => _EmailPageState();
}

class _EmailPageState extends State<EmailPage> {
  var _emailController = TextEditingController();
  var _verifyController = TextEditingController();

  User user;
  String title;
  bool isEdit = true;
  int step = -1;
  String submitStr = "确定";

  //倒计时按钮
  Timer _countTimer;
  String _btnStr = '获取验证码';
  int _count = 120;

  @override
  void initState() {
    super.initState();
    if (null == widget.email) {
      title = "绑定邮箱";
    } else {
      title = "校验邮箱";
      isEdit = false;
      step = 1;
      submitStr = "下一步";
    }
    _emailController.value = TextEditingValue(text: widget.email ?? "");
  }

  @override
  Widget build(BuildContext context) {
    user = Provide.value<User>(context);
    return Scaffold(
      appBar: AppBar(
        title: Text(title, style: TextStyle(fontSize: 18)),
        backgroundColor: Theme.of(context).cardColor,
      ),
      body: ListView(
          padding: EdgeInsets.symmetric(horizontal: 22.0),
          children: <Widget>[
            SizedBox(height: 40),
            buildPhoneTextField(),
            SizedBox(height: 20),
            buildVerifyTextField(),
            SizedBox(height: 40),
            buildVerifyButton(),
          ]),
    );
  }

  @override
  void dispose() {
    super.dispose();
    if (null != _countTimer) {
      _countTimer.cancel();
      _countTimer = null;
    }
  }

  Widget buildPhoneTextField() {
    return TextField(
      keyboardType: TextInputType.phone,
      controller: _emailController,
      decoration: InputDecoration(
        labelText: '邮箱',
        hintText: '请输入邮箱',
        enabled: isEdit,
        contentPadding: EdgeInsets.all(10),
        prefixIcon: Icon(Icons.email),
        border: OutlineInputBorder(
          borderSide: BorderSide(
            color: Theme.of(context).accentColor,
          ),
          borderRadius: BorderRadius.all(Radius.circular(24)),
        ),
      ),
    );
  }

  Widget buildVerifyTextField() {
    return TextField(
      keyboardType: TextInputType.number,
      controller: _verifyController,
      decoration: InputDecoration(
        labelText: '验证码',
        hintText: '请输入验证码',
        contentPadding: EdgeInsets.all(10),
        prefixIcon: Icon(Icons.lock),
        suffixIcon: FlatButton(
            onPressed: () {
              FocusScope.of(context).requestFocus(FocusNode());
              sendVerify(false);
            },
            child: Text(_btnStr,
                style: TextStyle(
                    color: _count == 120
                        ? Theme.of(context).accentColor
                        : Colors.black38))),
        border: OutlineInputBorder(
          borderSide: BorderSide(
            color: Theme.of(context).accentColor,
          ),
          borderRadius: BorderRadius.all(Radius.circular(24)),
        ),
      ),
    );
  }

  Widget buildVerifyButton() {
    return SizedBox(
      width: double.infinity,
      height: 44,
      child: RaisedButton(
        onPressed: () {
          sendVerify(true);
        },
        child: Text(
          submitStr,
          style: TextStyle(color: Colors.white),
        ),
        color: Theme.of(context).accentColor,
        shape: StadiumBorder(
          side: BorderSide(color: Theme.of(context).accentColor),
        ),
      ),
    );
  }

  ///发送验证码
  void sendVerify(bool isCheck) {
    String _email = _emailController.text;
    String _code = _verifyController.text;
    if (_email.isEmpty || !CommUtil.isEmail(_email)) {
      Toast.show("请填写正确的邮箱地址");
      return;
    }
    Map<String, String> params = Map();
    params["verifyTag"] = _email;
    String msg = "发送中...";
    if (isCheck) {
      msg = "验证中...";
      if (_code.isEmpty) {
        Toast.show("请输入验证码");
        return;
      }
      params["verifyCode"] = _code;
    }
    CancelFunc closeLoading = Toast.loading(msg);
    Http.post(Api.USER_CODE, params: params, successCallBack: (data) {
      closeLoading();
      if (!isCheck) {
        Toast.show("发送成功");
        countDownTimer();
      } else {
        if (step == 1) {
          _emailController.value = TextEditingValue(text: "");
          _verifyController.value = TextEditingValue(text: "");
          step = 2;

          setState(() {
            isEdit = true;
            title = "绑定新邮箱";
            submitStr = "确定";
            _btnStr = '获取验证码';
            _count = 120;
            _countTimer.cancel();
            _countTimer = null;
          });
        } else {
          Toast.show("绑定成功");
          if (null != user) {
            user.email = _email;
            user.update(user);
          }
          Navigator.of(context).pop();
        }
      }
    }, errorCallBack: (error) {
      closeLoading();
      Toast.show(error);
    });
  }

  ///倒计时按钮
  void countDownTimer() {
    if (_countTimer != null) {
      return;
    }
    _btnStr = '${_count--}s重新获取';
    _countTimer = Timer.periodic(Duration(seconds: 1), (timer) {
      print("$_count");
      setState(() {
        if (_count > 0) {
          _btnStr = '${_count--}s后重新获取';
        } else {
          _btnStr = '获取验证码';
          _count = 120;
          _countTimer.cancel();
          _countTimer = null;
        }
      });
    });
  }
}
